<?php
declare (strict_types = 1);

namespace app\adminapi\model\Admin;

use adminmatrix\admin\model\BaseModel;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * @mixin \think\Model
 */
class Admin extends BaseModel
{
    # 定义字段
    protected array $type = [
        'last_login_ip	'   =>  'int'
    ];

    protected array $hidden = ['password'];
    # 定义全局的查询范围
    protected array $globalScope  = [];

    #------------------------------------------------------------
    #
    #  查询范围
    #
    #------------------------------------------------------------
    # 默认不查询超级管理员
    public function scopeNotAdmin($query) : void
    {
        $query->whereNotIn('id' , [1]);
    }

    #------------------------------------------------------------
    #
    #   关联模型
    #
    #------------------------------------------------------------

    # 关联token
    public function session() : HasOne
    {
        return $this->hasOne(AdminSession::class , 'admin_id');
    }

    # 关联 权限
    public function role():HasMany
    {
        return $this->hasMany(AdminRoles::class , 'admin_id');
    }


    #------------------------------------------------------------
    #
    #   搜索器
    #
    #------------------------------------------------------------
    # 搜索管理严
    public function searchUserNameAttr($query , $value)
    {
        if (empty($value)) return '';
        $query->whereLike("username" , "%{$value}%");
    }

    # 搜索状态
    public function searchStatusAttr($query , $value)
    {
//        if (empty($value)) return '';
        $query->where('status' , $value);
    }

    public function searchCreateTimeAttr($query , $value)
    {
        if (empty($value)) return '';

    }

    #------------------------------------------------------------
    #
    #   模型赋值 set Attr
    #
    #------------------------------------------------------------
    # 设置ip
    public function setLastLoginIpAttr($ip) : int | null
    {
        if (empty($ip)) return NULL;
        return ip2long($ip);
    }
    #------------------------------------------------------------
    #
    #   模型取值get Attr
    #
    #------------------------------------------------------------

    # 读取ip
    public function getLastLoginIpAttr( $ip) : string
    {
        if (empty($ip)) return '';
        return long2ip((int)$ip);
    }

    # 转换最后登录时间为日期
    public function getLastLoginTimeAttr(  $time) : string
    {
        if (empty($time)) return  '';
        return  date("Y-m-d H:i:s" , $time);
    }
}
